//
//  UIImageView+Extension.m
//  TaduUtils
//
//  Created by Deheng Xu on 11-8-6.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "XWebImageView.h"

#if TARGET_OS_IPHONE

//#import "XUtils.h"
#import "FunctionSet.h"

@implementation XWebImageView

@synthesize connection;
@synthesize imageUrl;
@synthesize data;
//@synthesize favorite;
//@synthesize history;
@synthesize defaultIconName;
@synthesize activity;
@synthesize delegate;
@synthesize isNeedDecompress;
@synthesize imageType;


- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (id) initWithCoder:(NSCoder *)aDecoder
{
	self = [super initWithCoder:aDecoder];
    if (self) {
//        defaultIconName = [[NSString alloc] initWithFormat:@"暂无封面.png"];
//        TDResources * _res = [TDResources SharedResources];
//        NSArray * nameComponents = [defaultIconName componentsSeparatedByString:@"."];
//        [self setImage:[_res imageForName:[nameComponents objectAtIndex:0] Type:[nameComponents objectAtIndex:1]]];
        if (activity == nil) {
            activity = [UIActivityIndicatorView new];
        }
        activity.center = CGPointMake(self.frame.size.width / 2.0, self.frame.size.height / 2.0);
        [self addSubview:self.activity];
        [activity setHidden:YES];
    }
	return self;
}

- (id)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code.
//		defaultIconName = [[NSString alloc] initWithFormat:@"暂无封面.png"];
//        TDResources * _res = [TDResources SharedResources];
//        NSArray * nameComponents = [defaultIconName componentsSeparatedByString:@"."];
//        [self setImage:[_res imageForName:[nameComponents objectAtIndex:0] Type:[nameComponents objectAtIndex:1]]];
        if (activity == nil) {
            activity = [UIActivityIndicatorView new];
        }
        activity.center = CGPointMake(self.frame.size.width / 2.0, self.frame.size.height / 2.0);
        [self addSubview:self.activity];
        [activity setHidden:YES];
    }
    return self;
}

- (id)initWithDefaultImageName:(NSString *)imageName
{
    UIImage *img = [UIImage imageNamed:imageName];
//    if (!img) {
//        [self release];
//        return nil;
//    }    
    self = [super initWithImage:img];
    return self;
}

- (void) updateImage:(BOOL)force
{
    //NSLog(@"force :%@", NSStringFromBool(force));
	
	if (force) {
		[self startDownloading:imageUrl];
	}else {
        if (data) {
            [self setImage:[UIImage imageWithData:data]];
        }else if (defaultIconName.length > 0) {//调用默认值
            [self setImage:[UIImage imageNamed:defaultIconName]];
		}

        if (imageUrl) {
            [self startDownloading:imageUrl];
        }
	}
}

- (void) startDownloading:(NSString *)sUrl
{
	[self stopDownloading];
    [self.activity setHidden:NO];
	self.data = [NSMutableData data];
	NSLog(@"start downloading image:%@", sUrl);
    if (!sUrl) {
        NSLog(@"%s url is nil!", __FUNCTION__);
        return;
    }
	NSURL * url = [[NSURL alloc] initWithString:sUrl];
    NSMutableURLRequest * muRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    [muRequest setTimeoutInterval:10.0f];
	self.connection = XAutorelease([[NSURLConnection alloc] initWithRequest:muRequest delegate:self]);
    XRelease(url);
    XRelease(muRequest);
}

- (void)stopDownloading
{
    if (connection) {
        [connection cancel];
        SafeRelease(connection);
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code.
 }
 */

#if !ARC_ENABLED
- (void)dealloc {
	[connection cancel];
    SafeRelease(connection);
    SafeRelease(imageUrl);
    SafeRelease(data);
    SafeRelease(defaultIconName);
    SafeRelease(activity);
    SafeRelease(imageType);
    [super dealloc];
}
#endif

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"XWebImageView error:%@", error);
    if (error) {
        self.data = nil;
        [self.activity setHidden:YES];
    }
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if ([response respondsToSelector:@selector(allHeaderFields)]) {
        NSHTTPURLResponse * httpRespon = (NSHTTPURLResponse *) response;
        self.imageType = [httpRespon.allHeaderFields objectForKey:@"Content-Type"];
        isNeedDecompress = IsResponserCompressed(httpRespon.allHeaderFields);
    }
    self.data = [NSMutableData dataWithCapacity:512];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData
{
    if (data != nil) {
        [self.data appendData:aData];
    }
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
	//NSLog(@"%@ connection:%@", DEBUG_FUNCTION_NAME, self.connection);
	self.connection = nil;
	UIImage * img = XAutorelease([[UIImage alloc] initWithData:self.data]);
    //NSLog(@"img = %@", img);
	if (img == nil || self.data.length <= 0) {
		img = [UIImage imageNamed:defaultIconName];
	}
	
	self.image = img;
        
    if (data && delegate && [delegate respondsToSelector:@selector(webImageDownloaded:)]) {
        [delegate webImage:self downloaded:data];
    }
	
    [self.activity setHidden:YES];
}

- (void) setImage:(UIImage *) aImage
{
	if (image == nil) {
        if (defaultIconName.length == 0) {
            image = nil;
            return;
        }
        if (image) {
            XRelease(image);
        }
        image = nil;
	}else {
		[super setImage:aImage];
	}	
}

- (void)resetImage
{
    if (defaultIconName) {
        [self setImage:[UIImage imageNamed:defaultIconName]];
    }
    self.data = nil;
}

@end

#endif
